package com.jacobson.huobi

import android.app.Application
import android.content.Context
import android.webkit.WebSettings
import androidx.fragment.app.FragmentManager
import com.google.gson.GsonBuilder
import com.jacobson.core.App
import com.jacobson.core.base.delegate.AppLifecycle
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.di.modules.GlobalConfigurationModule
import com.jacobson.core.framework.AppConfiguration
import com.jacobson.core.framework.configuration.GsonConfiguration
import com.jacobson.core.framework.configuration.OkHttpClientConfiguration
import com.jacobson.core.framework.configuration.RetrofitConfiguration
import com.jacobson.core.framework.errorhandler.OnErrorListener
import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.core.widget.security.mgt.DefaultSecurityManager
import com.jacobson.huobi.HuobiApplication.Companion.getInstance
import com.jacobson.huobi.common.HttpAuthentication
import com.jacobson.huobi.common.config.HuobiRealm
import com.jacobson.huobi.common.expansion.toast
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit

/**
 * ================================================
 * APP配置
 * @see AndroidManifest.xml
 * @author Wucz on 2018/7/18 14:46
 * ================================================
 */

class HuobiAppConfiguration : AppConfiguration {
    private val realm = HuobiRealm()
    override fun applyOptions(context: Context, builder: GlobalConfigurationModule.Builder) {
        builder.apply {
            densitySupport { true }
            gsonConfiguration { applyGsonConfiguration() }
            okHttpClientConfiguration { applyOkHttpClientConfiguration() }
            retrofitConfiguration { applyRetrofitConfiguration() }
            securityManager { DefaultSecurityManager(realm) }
//            TODO dialogHandler { DialogHelper() }
            onErrorListener {
                object : OnErrorListener {
                    override fun onError(context: Context, e: Throwable) {
                        context.toast("请检查网络")
                    }
                }
            }
        }
    }

    override fun inject(context: Context, app: App, appComponent: AppComponent) {
        realm.inject(appComponent)
    }

    override fun injectAppLifecycle(context: Context, lifecycleList: MutableList<AppLifecycle>) {
        lifecycleList.add(object : AppLifecycle {
            override fun attachBaseContext(base: Context) {
            }

            override fun onCreate(application: Application) {
//                QbSdk.initX5Environment(application, null)

                //设置全局的Header构建器
                SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
                    layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white)//全局设置主题颜色
                    ClassicsHeader(context)//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
                }
                //设置全局的Footer构建器
                SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
                    //指定为经典Footer，默认是 BallPulseFooter
                    ClassicsFooter(context).setDrawableSize(20f)
                }
            }

            override fun onTerminate(application: Application) {
            }

        })
    }

    override fun injectActivityLifecycle(
        context: Context,
        lifecycleList: MutableList<Application.ActivityLifecycleCallbacks>
    ) {
    }

    override fun injectFragmentLifecycle(
        context: Context,
        lifecycleList: MutableList<FragmentManager.FragmentLifecycleCallbacks>
    ) {
    }


    private fun applyOkHttpClientConfiguration(): OkHttpClientConfiguration {

        return OkHttpClientConfiguration.build {
            readTimeout { 15000 }
            connectTimeout { 15000 }
            httpLoggerLevel { HttpLoggingInterceptor.Level.BODY }
            globalHttpHandler {
                object : OkHttpClientConfiguration.GlobalHttpHandler {
                    override fun onHttpRequestBefore(
                        chain: Interceptor.Chain,
                        request: Request
                    ): Request {
                        val newRequest = request.newBuilder()
                            .addHeader("Content-Type", "application/x-www-form-urlencoded")
                            .addHeader("User-Agent", WebSettings.getDefaultUserAgent(getInstance()))//添加app的user-agent,用来区分app和其他平台
                            .build()
                        LoggerFactory.getLogger("http").v("http->interceptor: -> $newRequest")
                        LoggerFactory.getLogger("http").v("http->interceptor: -> ${newRequest.headers()}")
                        //判断是否需要鉴权
                        return HttpAuthentication.authentication(newRequest)
                    }

                    override fun onHttpResultResponse(
                        httpResult: String,
                        chain: Interceptor.Chain,
                        response: Response
                    ): Response = response
                }
            }
        }
    }

    private fun applyRetrofitConfiguration(): RetrofitConfiguration {
        return RetrofitConfiguration.build {
            //            baseUrl { "http://192.168.50.56/app/" }
            baseUrl { Constants.APP_URL }
//            baseUrl { "http://192.168.10.128:8080/laymsg/" }
            onBuildInterceptor {
                object : RetrofitConfiguration.OnBuildInterceptor {
                    override fun onBuildIntercept(
                        application: Application,
                        builder: Retrofit.Builder
                    ) {

                    }
                }
            }
        }
    }

    private fun applyGsonConfiguration(): GsonConfiguration {
        return GsonConfiguration.build {
            onBuildInterceptor {
                object : GsonConfiguration.OnBuildInterceptor {
                    override fun onBuildIntercept(application: Application, builder: GsonBuilder) {
                        builder.setPrettyPrinting()
                    }
                }
            }
        }
    }
}
